package thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class MyBlockingQueue{

    private String[] data = null;

    // 队首
    private int head = 0;
    // 队尾
    private int tail = 0;
    // 元素个数
    private int size = 0;

    // 构造方法
    public MyBlockingQueue(int capacity) {
        data = new String[capacity];
    }

    // 入队列
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            if(size >= data.length){
                // 队列满了，需要阻塞
                this.wait();
                // return;
            }
            data[tail] = elem;
            tail++;
            // 如果tail指向队列末尾，将它设为头（循环队列）
            if(tail >= data.length){
                tail = 0;
            }
            size++;

            // 存在元素入队列，队列不空，唤醒take方法
            this.notify();
        }
    }

    // 出队列
    public String take() {
        synchronized (this){

            // wait语句执行前后都判断一下队列是否为空，防止wait被notify以外其他方法唤醒而导致程序出错
            while(size == 0){
                // 队列为空，需要阻塞等待
                try{
                    this.wait();
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String ret = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;

            // 存在元素出队列，队列不满了，唤醒put方法
            this.notify();
            return ret;
        }
    }
}
public class Demo23 {
    public static void main(String[] args) throws InterruptedException {

        MyBlockingQueue queue = new MyBlockingQueue(100);

        //生产者生产元素
        Thread producer = new Thread(()->{
            int n = 0;
            while(true){
                try {
                    queue.put(n + "");
                    System.out.println("生产元素" + n);
                    Thread.sleep(1000);
                    n++;
                } catch (InterruptedException e) {
                    throw new RuntimeException();
                }
            }
        },"producer");

        //消费者消费元素
        Thread consumer = new Thread(()->{
            while(true){
                try {
                    String n = queue.take();
                    System.out.println("消费元素" + n);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException();
                }
            }
        },"consumer");

        producer.start();
        consumer.start();
    }
}
